package com.eshopkeeper.core.util;

import com.alibaba.fastjson.JSONObject;
import com.eshopkeeper.core.util.yunzhi.StringUtil;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Author YiMing
 * @Description:
 * @Date: Created in 下午3:31 2017/11/9
 * @Modified By
 */
public final class WeChatUtil {

	public static final Logger logger = LogManager.getLogger(WeChatUtil.class);

	public static Map<String, String> sign(String jsapi_ticket, String url) {
		Map<String, String> ret = new HashMap<String, String>();
		String nonce_str = create_nonce_str();
		String timestamp = create_timestamp();
		String string1;
		String signature = "";

		//注意这里参数名必须全部小写，且必须有序
		string1 = "jsapi_ticket=" + jsapi_ticket +
				"&noncestr=" + nonce_str +
				"&timestamp=" + timestamp +
				"&url=" + url;
		System.out.println(string1);

		try
		{
			MessageDigest crypt = MessageDigest.getInstance("SHA-1");
			crypt.reset();
			crypt.update(string1.getBytes("UTF-8"));
			signature = byteToHex(crypt.digest());
		}
		catch (NoSuchAlgorithmException e)
		{
			e.printStackTrace();
		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}

		ret.put("url", url);
		ret.put("jsapi_ticket", jsapi_ticket);
		ret.put("nonceStr", nonce_str);
		ret.put("timestamp", timestamp);
		ret.put("signature", signature);

		return ret;
	}

	//获取token
	public static String getAccessToken(Map<String, String> map) {

		//组装数据
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&"); //https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&
		stringBuffer.append("appid=" + map.get("appId"));
		stringBuffer.append("&secret=" + map.get("appSecret"));

		//调用微信接口
		String access_token = HttpUtil.httpClientPost(stringBuffer.toString());
		JSONObject jsonObject = JSONObject.parseObject(access_token);

		access_token = jsonObject.getString("access_token");

		//判断是否获取成功
		if (StringUtil.isNotEmpty(access_token)) {

			logger.info("微信获取的accessToken是:" + access_token);
			//获取成功后将accessToken 放入redis缓存中
			RedisUtil.set("access_token",access_token,7000);

			return access_token;
		} else {
			return null;
		}
	}

	//获取ticket
	public static String getTicket(String accessToken) {

		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append("https://api.weixin.qq.com/cgi-bin/ticket/getticket?");
		stringBuffer.append("access_token=" + accessToken);
		stringBuffer.append("&type=jsapi");
		String ticket = HttpUtil.httpClientPost(stringBuffer.toString());

		JSONObject jsonObject = JSONObject.parseObject(ticket);
		ticket = jsonObject.getString("ticket");

		//判断是否获取成功
		if (StringUtil.isNotEmpty(ticket)) {

			logger.info("微信获取的cacheTicket是:" + ticket);
			//获取成功后将ticket放入redis缓存中
			RedisUtil.set("ticket", ticket,7000);

			return ticket;
		} else {
			return null;
		}
	}

	private static String byteToHex(final byte[] hash) {
		Formatter formatter = new Formatter();
		for (byte b : hash)
		{
			formatter.format("%02x", b);
		}
		String result = formatter.toString();
		formatter.close();
		return result;
	}

	//获取随机字符串
	private static String create_nonce_str() {
		return UUID.randomUUID().toString();
	}

	//获取当前时间
	private static String create_timestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}
}
